import { RedisBin } from 'coa-redis'
import Utils from "../utils/Utils";

const redisConfig = {
    // 服务器地址
    host: '127.0.0.1',
    // 端口
    port: 6379,
    // 密码，若无填空字符串
    password: '',
    // 数据库，默认为0
    db: 1,
    // 键前缀，可区分不同的项目
    prefix: '',
    // 是否显示查询语句
    trace: true,
}

export default class RedisClient {
    private redisInstance: RedisBin;

    constructor() {
        this.redisInstance = new RedisBin(redisConfig)
    }

    public async incr(key:string){
        let star:number = -1;
        if(!Utils.isEmpty(key)){
            await this.redisInstance.io.incr(key).then((result) => {
                star = <number><unknown>result;
            });
        }
        return star;
    }

    public async getStar(key:string){
        return <number><unknown>this.get(key);
    }

    public async get(key:string){
        let value:any;
        if(!Utils.isEmpty(key)){
            await this.redisInstance.io.get(key).then((result) => {
                value = result;
            });
        }
        return value;
    }


    public async mget(keys:string[]){
        let values:any;
        if(!Utils.isEmpty(keys) && keys.length > 0){
            await this.redisInstance.io.mget(keys).then((result) => {
                values = result;
            });
        }
        return values;
    }


    public async zincrby(key:string,member:string){
        let star:number = -1;
        if(!Utils.isEmpty(key) && !Utils.isEmpty(member)){
            await this.redisInstance.io.zincrby(key,1,member).then((result) => {
                star = <number><unknown>result;
            });
        }
        return star;
    }

    public async zscore(key:string,member:string){
        var star:number = 0 ;
        if(!Utils.isEmpty(key) && !Utils.isEmpty(member)){
            await this.redisInstance.io.zscore(key,member).then((result) => {
                star = <number><unknown>result;
            });
        }
        return star;
    }

    public async zpage(key:string,start:number,end:number){
        let result = {};
        if(!Utils.isEmpty(key) && start >= 0 && end > start){
            // @ts-ignore
            await this.redisInstance.io.zrevrange(key,start,end,'withscores').then((elements) => {
                for(var i=0;i<elements.length;i+=2){
                    // @ts-ignore
                    result[elements[i]] = elements[i+1];
                }
            });
        }
        return result;
    }

}

